﻿using AngleSharp.Html.Parser;
using DotnetSpider.Core;
using DotnetSpider.Core.Scheduler;
using SpiderPlatform.Dao;
using SpiderPlatform.Entity;
using SpiderPlatform.Pipe;
using SpiderPlatform.Processor;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using Yamibuy.Framework.Core.Tools;
using System.Linq;
namespace SpiderPlatform.Service
{
    public class KouhighService
    {
        string apiService = "https://kh.kouhigh.com/app2_6/search/search";
        ItemDao dao = new ItemDao();

        public DateTime? CurrentDay { get; set; }
        public bool OnlyMail { get; set; }

        public DateTime TodayTime
        {
            get
            {

                DateTime todaytime = DateTime.Today;
                if (CurrentDay.HasValue)
                {
                    todaytime = CurrentDay.Value;
                }
                return todaytime;
            }
        }
        public void doWork()
        {          
            List<KouhighEntity> res = new List<KouhighEntity>();
            int page_index = 1;
            do
            {
                res = GetProductList(page_index);
                ImportData(res, page_index);
                page_index++;
            } while (res.Count>0);
          
            Logger.Info("数据导入完成");
        }


        private void ImportData(List<KouhighEntity> list,int page)
        {
          
            List<ChannelItemHistoryEntity> hisList = new List<ChannelItemHistoryEntity>();
            foreach (var item in list)
            {             
                hisList.Add(new ChannelItemHistoryEntity
                {
                    channel_id = 6,
                    channel_sku = item.id,
                    score = 0,
                    is_instock = item.is_instock,
                    reviews = 0,
                    price = decimal.Parse(item.price.TrimStart('$')),
                    title = item.name,
                    link = item.link,
                    images = item.images,
                    description = ""                  
                });
            }
            Logger.Info($"开始导入商品信息...，共{hisList.Count}条");
            if (hisList.Count == 0)
            {
                return;
            }
            hisList = hisList.Distinct(new ChannelItemHistoryComparer()).ToList();
            
            dao.CreateChannelItemHistory(hisList);
            var hisExists = dao.QueryChannelItemBySku(6, hisList.Select(p => p.channel_sku).ToList());           

            //检查是否有新的商品出现
            var diffList = hisList.Except(hisExists, new ChannelItemHistoryComparer());
            //记录新的item   
            var newItemList = diffList.ToList().ToTypeList<ChannelItemHistoryEntity, ChannelItemEntity>();        
            Logger.Info($"检查新商品...，共{newItemList.Count}条");
            if (newItemList.Count > 0)
            {
                Logger.Info($"导入新商品step1...");
                dao.CreateChannelItem(newItemList);
                var realList = diffList.ToList();
                Logger.Info($"导入新商品step2...");
                dao.CreateChannelItemRealTime(realList);
            }
            Logger.Info($"更新商品信息...");
            dao.UpdateChannelItemRealTime(hisList);
            Logger.Info($"第{page}页任务完成");
        }

        private List<KouhighEntity> GetProductList(int page)
        {
            List<KouhighEntity> result = new List<KouhighEntity>();
            HttpClient client = new HttpClient();
            var postData =new
            {
                limit=100,
	            page= page,
	            lang="zh",
	            t=4
            };
            HttpContent httpContent = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(postData));
            //设置Http的内容标头
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json") { CharSet="utf-8"};
            var res = client.PostAsync(apiService, httpContent).Result;
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(data);
               // Console.WriteLine(temp.message);
                foreach (var item in temp.content.goods.goods)
                {
                    KouhighEntity entity = new KouhighEntity
                    {
                        name = item.name,
                        id=item.goods_id,
                        images=item.cover,
                        price=item.price,
                        is_instock=item.stock,
                        link= "https://www.kouhigh.com/goodDetail.html?goods_id=" + item.goods_id
                    };
                    result.Add(entity);
                }
            }          
            return result;
        }
    }
}
